<template>
    <div class="bg flex">
        <div class="content-div">

            <!-- 头部 -->
            <div class="article_head flex-float">
                <h1>留言</h1>
                <div class="flex">
                    <el-button @click="addArticleDrawer = true" class="creat_btn" type="primary">发布留言</el-button>
                    <el-input v-model="input1" style="width: 240px" size="large" placeholder="搜索" :suffix-icon="Search"
                        @change="search_handler" />
                </div>
            </div>
            <!-- 表单 -->
            <el-table highlight-current-row :data="tableData" height="250" style="width: 100%"
                @row-click="row_click_handler">
                <el-table-column prop="title" label="标题" width="300" />
                <el-table-column prop="article_id" label="留言编号" width="300" />
                <el-table-column prop="likes" label="点赞数" />
            </el-table>
            <!-- 抽屉 -->
            <el-drawer size="90%" v-model="drawer" title="留言详情" direction="ttb" :before-close="handleClose">
                <div v-if="currentArticle">
                    <div class="divdiv">
                        <div class="flex-float">
                            <h2>{{ currentArticle.title }}</h2>
                            <p>留言编号: {{ currentArticle.article_id }}</p>
                        </div>
                        <div class="article_content">
                            <p>{{ currentArticle.content }}</p>
                        </div>
                        <div class="flex-float">
                            <p>作者编号: {{ currentArticle.author_id }}</p>
                            <el-button type="danger" @click="showAuthorInfo">查看作者详细信息</el-button>
                            <div class="flex">
                                <el-button class="like_btn" @click="like_handler" type="danger">{{ currentArticle.likes
                                    }}<el-icon>
                                        <Star />
                                    </el-icon></el-button>
                                <el-button type="danger"
                                    @click="delete_article_handler(currentArticle.article_id, currentUsername)">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </el-button>
                            </div>
                        </div>
                    </div>
                    <el-button type="danger" @click="getComment_handler">展开评论区</el-button>
                </div>
                <!-- 子抽屉-评论区 -->
                <el-drawer size="60%" v-model="commentDrawer" title="评论区" direction="btt" :append-to-body="true"
                    :before-close="handleCommentClose">
                    <div class="comment-section flex">
                        <el-input class="commentInput" v-model="newComment" type="textarea" placeholder="写下你的评论" size="large"/>
                        <hr/>
                        <el-button class="commentBtn" type="primary" @click="postComment">发布评论</el-button>
                    </div>
                    <div v-if="currentComments.length">
                        <h2>评论</h2>
                        <ul>
                            <li v-for="comment in parentComments" :key="comment.comment_id" class="comment-item">
                                <div class="comment-content">
                                    <p><strong>{{ comment.username }}</strong>: {{ comment.content }}</p>
                                    <div>
                                        <el-button type="primary" @click="likeComment(comment.comment_id)">
                                            {{ comment.likes }}
                                            <el-icon>
                                                <Star />
                                            </el-icon></el-button>
                                        <el-button type="success" @click="replyToComment(comment.comment_id)"><el-icon>
                                                <Comment />
                                            </el-icon></el-button>
                                    </div>
                                </div>
                                <ul v-if="comment.replies" class="reply-list">
                                    <li v-for="reply in comment.replies" :key="reply.comment_id" class="reply-item">
                                        <div class="comment-content">
                                            <p><strong>{{ reply.username }}</strong>: {{ reply.content }}</p>
                                            <div>
                                                <el-button type="primary" @click="likeComment(reply.comment_id)">
                                                    {{ reply.likes }}
                                                    <el-icon>
                                                        <Star />
                                                    </el-icon></el-button>
                                                <el-button type="success"
                                                    @click="replyToComment(reply.comment_id)"><el-icon>
                                                        <Comment />
                                                    </el-icon></el-button>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                            </li>
                        </ul>
                    </div>
                    <div v-else>
                        <p>当前无评论，快来评论吧！</p>
                    </div>
                </el-drawer>

                <!-- 子抽屉-作者 -->
                <el-drawer v-model="authorDrawer" title="作者信息" direction="rtl" :append-to-body="true"
                    :before-close="handleAuthorClose">
                    <div v-if="currentAuthor.value && Object.keys(currentAuthor.value).length">
                        <p>作者编号: {{ currentAuthor.id }}</p>
                        <p>作者姓名: {{ currentAuthor.value.username }}</p>
                        <p>作者昵称: {{ currentAuthor.value.nickname }}</p>
                        <p>作者邮箱: {{ currentAuthor.value.email }}</p>
                    </div>
                    <div v-else>
                        <p>正在加载作者信息...</p>
                    </div>
                </el-drawer>


            </el-drawer>
            <!-- 抽屉-发留言 -->
            <el-drawer size="50%" v-model="addArticleDrawer" title="发布留言" direction="ttb" :append-to-body="true"
                :before-close="handleAddArticleDrawerClose">
                <div>
                    <!-- 表单 -->
                    <el-form :model="newArticle">
                        <el-form-item label="留言标题">
                            <el-input v-model="newArticle.title" placeholder="请输入留言标题"></el-input>
                        </el-form-item>
                        <el-form-item label="留言内容">
                            <el-input type="textarea" v-model="newArticle.content" placeholder="请输入留言内容"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitArticle">提交</el-button>
                            <el-button @click="handleAddArticleDrawerClose">取消</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-drawer>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import { Search } from '@element-plus/icons-vue';
import { useStore } from 'vuex'
import {
    getArticles,
    getCommentsByArticleId,
    likeArticle,
    likeCommentAPI,
    deleteArticleAPI,
    addArticles,
    addComments,
    searchArticles,
    getUserInfoById,
} from "@/util/request"

export default {
    name: 'Message',
    setup() {
        const store = useStore()
        const tableData = reactive([]); // 表格数据
        const input1 = ref(''); // 搜索输入框的值
        const drawer = ref(false); // 控制留言详情抽屉的显示
        const commentDrawer = ref(false); // 控制评论区抽屉的显示
        const authorDrawer = ref(false); // 控制作者信息抽屉的显示
        const addArticleDrawer = ref(false); // 控制发留言抽屉的显示
        const currentArticle = ref(null); // 当前选中的留言
        const currentAuthor = reactive({ id: '', value: {} }); // 当前留言的作者信息
        const currentComments = ref([]); // 当前留言的评论
        const parentComments = ref([]); // 父评论列表
        const newArticle = reactive({ title: '', content: '' }); // 新留言
        const newComment = ref(''); // 新评论内容
        const replyTo = ref(null); // 当前回复的评论
        const currentUsername = store.state.uInfo.userInfo.username;
        const currentUserId = localStorage.getItem("userId");

        // 搜索处理函数
        const search_handler = async () => {
            if (input1.value.trim() === '') {
                // 如果搜索框为空，重新加载所有留言
                await loadArticles();
                return;
            }

            try {
                const res = await searchArticles(input1.value);
                if (res.status === 0) {
                    tableData.splice(0, tableData.length, ...res.data); // 清空表格数据并替换成搜索结果
                } else {
                    console.error("搜索留言失败", res.message);
                }
            } catch (error) {
                console.error("搜索留言时发生错误", error);
            }
        }

        // 加载留言数据
        const loadArticles = async () => {
            const res = await getArticles();
            if(res.data){
                tableData.splice(0, tableData.length, ...res.data); // 清空表格数据并添加新的留言
            }
        }

        // 组件挂载后加载留言数据
        onMounted(() => {
            loadArticles();
        })

        // 表格行点击处理函数
        const row_click_handler = (row) => {
            currentArticle.value = row;
            drawer.value = true;
        }

        // 获取评论处理函数
        const getComment_handler = async () => {
            const res = await getCommentsByArticleId(currentArticle.value.article_id);
            currentComments.value = res.data;
            processComments();
            commentDrawer.value = true;
        }

        // 处理评论，构建父子关系
        const processComments = () => {
            const commentMap = {};
            currentComments.value.forEach(comment => {
                commentMap[comment.comment_id] = { ...comment, replies: [] };
            });
            const tempParentComments = [];
            currentComments.value.forEach(comment => {
                if (comment.parent_comment_id === null) {
                    tempParentComments.push(commentMap[comment.comment_id]);
                } else if (commentMap[comment.parent_comment_id]) { // 检查父评论是否存在
                    commentMap[comment.parent_comment_id].replies.push(commentMap[comment.comment_id]);
                }
            });
            parentComments.value = tempParentComments;
        }

        // 关闭留言详情抽屉处理函数
        const handleClose = () => {
            drawer.value = false;
        }

        // 关闭评论区抽屉处理函数
        const handleCommentClose = () => {
            commentDrawer.value = false;
        }

        // 关闭作者信息抽屉处理函数
        const handleAuthorClose = () => {
            authorDrawer.value = false;
        }

        // 关闭添加留言抽屉处理函数
        const handleAddArticleDrawerClose = () => {
            addArticleDrawer.value = false;
        }

        // 点赞留言
        const like_handler = async () => {
            const res = await likeArticle(currentArticle.value.article_id);
            if (res.status === 0) {
                currentArticle.value.likes += 1;
            }
        }

        // 点赞评论处理函数
        const likeComment = async (commentId) => {
            const res = await likeCommentAPI(commentId);
            if (res.status === 0) {
                const comment = findCommentById(commentId);
                if (comment) {
                    comment.likes += 1;
                }
            }
        }

        // 根据评论ID查找评论
        const findCommentById = (commentId) => {
            for (const comment of currentComments.value) {
                if (comment.comment_id === commentId) {
                    return comment;
                }
                if (comment.replies && Array.isArray(comment.replies)) {
                    for (const reply of comment.replies) {
                        if (reply.comment_id === commentId) {
                            return reply;
                        }
                    }
                }
            }
            return null;
        }

        // 删除留言
        const delete_article_handler = async (articleId, username) => {
            console.log(articleId, username)
            try {
                const res = await deleteArticleAPI(articleId, username);
                if (res.status === 0) {
                    const index = tableData.findIndex(article => article.article_id === articleId);
                    if (index !== -1) {
                        tableData.splice(index, 1);
                    }
                    if (currentArticle.value && currentArticle.value.article_id === articleId) {
                        drawer.value = false;
                        currentArticle.value = null;
                    }
                    console.log("留言删除成功");
                } else {
                    console.error("删除留言失败", res.message);
                }
            } catch (error) {
                console.error("删除留言时发生错误", error);
            }
        }

        // 发布留言
        const submitArticle = async () => {
            try {
                const res = await addArticles(newArticle.title, newArticle.content, currentUserId);
                if (res.status === 0) {
                    console.log("留言发布成功");
                    addArticleDrawer.value = false;
                    window.location.reload();
                } else {
                    console.error("发布留言失败", res.message);
                }
            } catch (error) {
                console.error("发布留言时发生错误", error);
            }
        }

        // 发布评论
        const postComment = async () => {
            try {
                const content = newComment.value.startsWith("回复")
                    ? newComment.value.split("：")[1]
                    : newComment.value;

                const parentCommentId = replyTo.value ? replyTo.value.comment_id : null;
                const res = await addComments(currentArticle.value.article_id, currentUserId, content, parentCommentId);
                if (res.status === 0) {
                    console.log("评论发布成功");
                    newComment.value = ''; // 清空输入框
                    replyTo.value = null; // 清空回复对象
                    getComment_handler(); // 刷新评论列表
                } else {
                    console.error("发布评论失败", res.message);
                }
            } catch (error) {
                console.error("发布评论时发生错误", error);
            }
        }

        // 处理回复评论
        const replyToComment = (commentId) => {
            const comment = findCommentById(commentId);
            if (comment) {
                // 判断是否是重复点击同一个评论
                if (replyTo.value && replyTo.value.comment_id === comment.comment_id) {
                    replyTo.value = null;
                    newComment.value = '';
                } else {
                    replyTo.value = comment;
                    newComment.value = `回复 ${comment.username}：`; // 在评论框中添加回复提示
                }
            }
        }

        // 显示作者信息处理函数
        const showAuthorInfo = async () => {
            try {
                const res = await getUserInfoById(currentArticle.value.author_id);
                if (res.status === 0) {
                    currentAuthor.id = currentArticle.value.author_id;
                    currentAuthor.value = res.data;
                    authorDrawer.value = true;
                } else {
                    console.error("获取作者信息失败", res.message);
                }
            } catch (error) {
                console.error("获取作者信息时发生错误", error);
            }
        }

        // watch(currentAuthor, (newVal, oldVal) => {
        //     if (newVal) {
        //         console.log('Author data updated:', newVal);
        //         authorDrawer.value = true;
        //     }
        // });


        return {
            input1,
            tableData,
            Search,
            search_handler,
            loadArticles,
            drawer,
            commentDrawer,
            authorDrawer,
            currentArticle,
            currentAuthor,
            currentComments,
            parentComments,
            newArticle,
            newComment,
            replyTo,
            row_click_handler,
            getComment_handler,
            processComments,
            handleClose,
            handleCommentClose,
            handleAuthorClose,
            handleAddArticleDrawerClose,
            like_handler,
            likeComment,
            findCommentById,
            delete_article_handler,
            currentUsername,
            submitArticle,
            currentUserId,
            addArticleDrawer,
            postComment,
            replyToComment,
            showAuthorInfo,
        };
    }
}
</script>

<style scoped>
.bg {
    width: 100%;
    height: 100%;
    margin: 0;
    background: linear-gradient(45deg, #ffc107, deeppink, #9c27b0);
    animation: hueRotate 10s infinite alternate;
    overflow: scroll;
}

@keyframes hueRotate {
    100% {
        filter: hue-rotate(360deg);
    }
}

.title {
    font-size: 50px;
    text-align: center;
}
</style>

<style scoped>
.content-div {
    position: relative;
    z-index: 1;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 15px;
    margin: auto;
    padding: 50px;
    margin-top: 100px;
    height: auto;
    width: 80%;
    border: 2px solid;
}

.article_head {
    font-size: 30px;
    text-align: center;
    margin-bottom: 20px;
}

.creat_btn {
    margin-right: 10px;
}

.example-pagination-block+.example-pagination-block {
    margin-top: 10px;
}

.divdiv {
    margin-right: 300px;
}

.article_content {
    border: 2px solid;
    border-radius: 15px;
    padding: 20px;
}

.like_btn {
    margin-left: 20px;
}

.comment-item {
    margin-bottom: 15px;
    padding-left: 10px;
    border-left: 2px solid #ddd;
}

.reply-list {
    margin-left: 20px;
    padding-left: 10px;
    border-left: 1px solid #ddd;
}

.reply-item {
    margin-bottom: 10px;
}

.comment-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.comment-section {
    margin-bottom: 20px;
}
.commentBtn{
    margin-left: 10px;
}
.commentInput{
    margin: 10px;
}
</style>
